/*
 * Copyright 2009 Tran Nhut Trung.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package org.eclipse.core.databinding.observable.gwt.internal;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.ListBox;

import org.eclipse.core.databinding.observable.Realm;

public class ListBoxObservableValue extends WidgetPropertyObservableValue {
  protected ListBox listBox;

  private ChangeHandler changeHandler = new ChangeHandler(){
    public void onChange(ChangeEvent event) {
      int index = listBox.getSelectedIndex();
      if (index >= 0){
        processUpdate(listBox.getValue(index));
      }else{
        processUpdate(null);
      }
    }
  };
  private HandlerRegistration changeHandlerRegistration;
  
  public ListBoxObservableValue(ListBox listBox) {
    this(Realm.getDefault(), listBox);
  }
  public ListBoxObservableValue(Realm realm, ListBox listBox) {
    super(realm, listBox, "value");
    
    this.listBox = listBox;
    
    changeHandlerRegistration = listBox.addChangeHandler(changeHandler);
  }

  public synchronized void dispose() {
    super.dispose();
    
    changeHandlerRegistration.removeHandler();
  }

  public Object doGetValue() {
    int index = listBox.getSelectedIndex();
    
    if (index >= 0){
      return listBox.getValue(index);
    }
    return null;
  }
  protected void doSetApprovedValue(Object value) {
    try {
      updating = true;
      
      if (value == null){
        listBox.setSelectedIndex(-1);
      }else{
        for (int i=0; i<listBox.getItemCount(); i++){
          if (value.equals(listBox.getValue(i))){
            listBox.setSelectedIndex(i);
            break;
          }
        }
      }
      
      this.oldValue = doGetValue();
    } finally {
      updating = false;
    }
  }
}
